# encoding: utf-8
# @Time    : 2021/2/4 4:37 下午
# @Author  : Sail
# @File    : views.py
# @Software: PyCharm
import pymongo

from . import cron
from ... import scheduler, monitor_mongo

from ...libs import const, result
from ..monitor.service import monitor_service
from .cron import implementRequest


@cron.route('/cron_index', methods=["GET"])
def index():
    return "this is cron index page"


@cron.route('/scheduler_status', methods=["GET"])
def scheduler_status():
    """
    查询定时器是否开启状态
    """
    scheduler_s = monitor_mongo.db.scheduler.find()
    l = list(scheduler_s)
    if l:
        status = l[0]["status"]
    else:
        status = False
    return result(const.SUCCESS, const.QUERY_SUCCESS, status)


@cron.route('/start_scheduler', methods=["GET"])
def start_scheduler():
    """
    开始整个定时器的执行
    """
    try:
        scheduler.start()
        dic = {"status": False}
        monitor_mongo.db.scheduler.update(dic, {'$set': {"status": True}}, True)
        return result(const.SUCCESS, "scheduler启动成功", True)
    except:
        return result(const.FAIL_40000, "scheduler启动失败", False)


@cron.route('/stop_scheduler', methods=["GET"])
def stop_scheduler():
    try:
        scheduler.shutdown()
        dic = {"status": True}
        monitor_mongo.db.scheduler.update(dic, {'$set': {"status": False}})
        return result(const.SUCCESS, "scheduler关闭成功", False)
    except:
        return result(const.FAIL_40000, "scheduler关闭失败", True)


@cron.route('/start_cron/<project_id>', methods=["GET"])
def start_cron(project_id):
    """
    project_id： 需要启动监控的项目id
    此方法用于对指定项目开始监控
    """
    scheduler_s = monitor_mongo.db.scheduler.find()
    l = list(scheduler_s)
    status = False
    if l:
        status = l[0]["status"]
    if not status:
        myclient = pymongo.MongoClient("mongodb://port:27017/")
        mydb = myclient["monitor"]
        mycol = mydb["task"]
        ret = mycol.find_one({"project_id": project_id})
        return result(const.FAIL_40000, "scheduler未启动，任务启动失败！", None)
        job = scheduler.add_job(func=implementRequest, trigger="interval", id=project_id, seconds=3, replace_existing=False,
                                args=(project_id,))
    if job.id != project_id:
        return result(const.FAIL_40000, "启动失败", None)
    else:
        monitor_mongo.db.task.update({"_id": int(project_id)}, {'$set': {"is_start": 1}})
        return result(const.SUCCESS, "项目监控启动成功", None)


@cron.route('/remove_specified_item/<project_id>', methods=["GET"])
def remove_specified_item(project_id):
    """
      project_id： 项目id
      此方法用于对指定项目移除定时任务
      """
    try:

        scheduler.remove_job(project_id)
        monitor_mongo.db.task.update({"_id": int(project_id)}, {'$set': {"is_start": 0}})
        return result(const.SUCCESS, "项目监控已停止", None)
    except:
        return result(const.FAIL_40000, "操作失败", None)
